/*
 * IOManager.cpp
 *
 *  Created on: 07/10/2012
 *      Author: vagner
 */

#include "IOManager.h"
#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>

IOManager::IOManager() {
	this->inputFile = new std::ifstream();
	this->outputFile = new std::ofstream();
}

IOManager::~IOManager() {
	//std::cout <<"Executando Destruidor IOMnager"<< std::endl;
	if(inputFile->is_open()){
		fechaArquivoEntrada();
	}

	if(outputFile->is_open()){
		fechaArquivoSaida();
	}
	delete inputFile;
	delete outputFile;
}

void IOManager::abreArquivoEntrada(const std::string& nomeArquivo){
	if(inputFile->is_open()){
		inputFile->close();
		inputFile->open(nomeArquivo.c_str());
	}else{
		inputFile = new std::ifstream(nomeArquivo.c_str());
	}
}
void IOManager::abreArquivoSaida(const std::string& nomeArquivo){
	if(outputFile->is_open()){
		outputFile->close();
		inputFile->open(nomeArquivo.c_str(),std::ios::app);
	}else{
		outputFile =  new std::ofstream(nomeArquivo.c_str(),std::ios::app);
	}
}

std::string IOManager::leiaProxLinha(void) const{

	std::string linha = "EOF";

	if(!inputFile->is_open()){
		//Não há arquivo aberto
		std::cout << "O arquivo de entrada não está aberto. Favor execuar o comando "
				<< "void IOManager::abreArquivoEntrada(const std::string& nomeArquivo)"
				<< "antes de tentar ler o arquivo. O programa será encerrado!!"<< std::endl;

	}else if( inputFile->good()){

		std::getline(*inputFile,linha);
	}
	return linha;
}

void IOManager::fechaArquivoEntrada(){
	if(inputFile->is_open()){
		inputFile->close();
	}
}
void IOManager::fechaArquivoSaida(){
	if(outputFile->is_open()){
		outputFile->close();
	}
}
void IOManager::escreveArquivoSaida(const std::string& saida) const{
	if(outputFile->is_open()){
		*outputFile << saida << std::endl;

	}
}
bool IOManager::validaEntrada(int& numArgs){

	bool rc = false;

	if(numArgs == 5){
		rc = true;
	}
	return rc;
}

void IOManager::splitEmVetor(std::string& s, std::vector<char>& listaChar){

	std::stringstream ss(s);
	std::string sub;
	char delim = ' ';
	while(std::getline(ss,sub,delim)){
		listaChar.push_back(sub[0]);
	}
}

void IOManager::splitEmVetor(std::string& s, std::vector<int>& listaInt){

	std::stringstream ss(s);
	std::string sub;
	char delim = ' ';
	while(std::getline(ss,sub,delim)){
			listaInt.push_back(std::atoi(sub.c_str()));
	}
}
